package review;

import org.junit.Test;

public class BubbleSort {
    @Test
    public void test() {
        int[] nums = {1, 3, 2, 4, 5, 7, 6, 8, 9, 0};
        bubble(nums);
        for (int num : nums) {
            System.out.print(num+" ");
        }
    }

    public void bubble(int[] a) {
        for (int i = 0; i < a.length - 1; i++) {          //一共需要比较length-1趟
            boolean flag = false;
            for (int j = 0 ; j < a.length - i - 1; j++) { //每一轮比较都会将大数沉底，小数会逐渐浮到顶端
                if (a[j] > a[j + 1]) {
                    swap(a, j, j + 1);
                    flag = true;
                }
            }
            if (!flag) {
                break;
            }
        }
    }

    public void swap(int[] a, int i, int j) {
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }
}
